<template>
  <SuperTable :data-request="fetchData" :columns="baseColumns" header-title="审批管理" pager align="center" border
    ref="supertable" :export-config="{}">
    <template #action>
      <a-button type="primary" @click="visibleloading = true">新增审批流程</a-button>
    </template>
  </SuperTable>
  <a-drawer destroyOnClose :footerStyle="{ display: 'flex', justifyContent: 'center' }" title="审批流程" width="60%"
    :visible="visibleloading" @close="onClose">
    <div style="display: flex; height: 100%">
      <div class="left">
        <a-form ref="formRef" style="width: 100%" :model="formState" name="basic" :label-col="{ span: 7 }"
          :wrapper-col="{ span: 15 }" autocomplete="off">
          <a-form-item name="flowPathType" label="审批配置类型" :rules="[{ required: true, message: '审批配置类型不能为空' }]">
            <a-select v-model:value="formState.flowPathType" :options="areas" />
          </a-form-item>
          <a-form-item name="flowPathName" label="审批名称" :rules="[{ required: true, message: '审批名称不能为空' }]">
            <a-input v-model:value="formState.flowPathName" placeholder="请输入审批名称" />
          </a-form-item>
          <a-form-item name="isSign" label="是否需要手写签字">
            <a-radio-group v-model:value="formState.isSign">
              <a-radio :value="1">是</a-radio>
              <a-radio :value="0">否</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
        <div class="lan">
          <p>开始</p>
          <p class="bjin">流程开始</p>
        </div>
        <div style="width: 0; height: 100px; border: #ccc 1px solid"></div>
        <div class="lan" style="background-color: #faad14">
          <p>审批人</p>
          <p class="bjin" style="border: #fde4b3 1px solid">选择审批人 <right-outlined class="icon" /></p>
        </div>
        <div style="width: 0; height: 100px; border: #ccc 1px solid"></div>
        <p style="color: rgb(102, 99, 99)">流程结束</p>
      </div>
      <div style="flex: 3; height: 90%">
        <div style="height: 25%">
          <a-form style="width: 100%" :model="formState" name="basic" :label-col="{ span: 6 }" :wrapper-col="{ span: 15 }"
            autocomplete="off">
            <a-form-item name="auditType" label="多人审批时的审批方式">
              <a-radio-group v-model:value="formState.manageLinkList[0].auditType">
                <a-radio :style="radioStyle" :value="0">按选择顺序依次审批</a-radio>
                <a-radio :style="radioStyle" :value="1">会签 (可同时审批,每个人必须同意)</a-radio>
                <a-radio :style="radioStyle" :value="2">或签 (有一人同意即可)</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item name="auditType" label="审批人">
              <a-radio-group v-model:value="formState.auditType2">
                <a-radio :style="radioStyle" value="2">指定人员</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-form>
          <p style="padding-left: 12px">选择人员</p>
        </div>
        <div style="height: 75%; overflow: auto">
          <a-transfer :list-style="{
            width: '300px',
            height: '100%',
            border: 0,
          }" v-model:target-keys="targetKeys" :data-source="mockData" show-search :filter-option="filterOption"
            :render="(item) => item.title" @change="handleChange" @search="handleSearch" />
        </div>
      </div>
    </div>
    <template #footer>
      <a-button style="margin-right: 15px" @click="onClose">取消</a-button>
      <a-button type="primary" @click="submit">保存</a-button>
    </template>
  </a-drawer>
</template>

<script setup lang="tsx">
import { ref, reactive, onMounted } from 'vue';
import SuperTable from '@/framework/components/core/super-table/super-table.vue';
import { getList, getAddList, getPutList, getDelList } from '../../api/approval_management';
import columns, { TableColumnList } from './columns';
import { RightOutlined } from '@ant-design/icons-vue';
import { userList } from '@/api/user-data';
import { message, Modal } from 'ant-design-vue';
import { VxeGridPropTypes } from 'vxe-table';
const formRef = ref();
const supertable = ref();
const fetchData = async (ori: VxeGridPropTypes.ProxyAjaxQueryParams) => {
  let queryparams: any = {
    pageSize: ori.page.pageSize,
    pageNum: ori.page.currentPage,
    orderBy: [
      {
        field: 'createTime',
        order: 'desc',
      },
    ],
    paging: false,
  };
  let { result } = await getList(queryparams);
  return result;
};
let addOrRenew = 0;
let baseColumns: TableColumnList = [
  ...columns,
  {
    title: '操作',
    field: '$action',
    hideInSearch: true,
    align: 'center',
    fixed: 'right',
    width: 300,
    actions: ({ row }) => [
      {
        label: '编辑',
        onClick: async () => {
          formState.flowPathType = row.flowPathType;
          formState.flowPathName = row.flowPathName;
          formState.isSign = row.isSign;
          addOrRenew = row.id;
          visibleloading.value = true;
          formState.manageLinkList[0].node = row.manageLinkList[0].node;
          formState.manageLinkList[0].auditType = row.manageLinkList[0].auditType;
          let arr = row.manageLinkList[0].auditUserId.split(',');
          let keys = mockData.value.map((item) => item.key);
          let newAuditUserId = [];
          arr.forEach((item) => {
            if (keys.includes(item)) {
              newAuditUserId.push(item);
            }
          });
          formState.manageLinkList[0].auditUserId = newAuditUserId.join(',');
          targetKeys.value = newAuditUserId;
        },
      },
      {
        label: '删除',
        onClick: async () => {
          Modal.confirm({
            title: '确认删除吗?',
            onOk: async () => {
              try {
                await getDelList(row.id);
                supertable.value?.refreshTable();
              } catch (errorInfo) {
                console.log('Failed:', errorInfo);
              }
            },
            onCancel() {
              console.log('Cancel');
            },
          });
        },
      },
    ],
  },
];
const visibleloading = ref(false);
const formState = reactive({
  flowPathType: 1,
  flowPathName: '',
  isSign: 0,
  auditType2: '2',
  manageLinkList: [
    {
      node: '1', //节点编号
      auditType: 0, //审批方式 0：按顺序审批；1：会签；2：或签
      auditUserId: '', //审批人，多人用逗号隔开
    },
  ],
});
const areas = [
  { label: '双人双锁配置', value: 1 },
  { label: '审批流程配置', value: 2 },
];
const onClose = () => {
  visibleloading.value = false;
  formRef.value.resetFields();
  formRef.value.clearValidate();
  targetKeys.value = [];
  addOrRenew = 0;
  formState.flowPathType = 1
  formState.isSign = 0
  formState.flowPathName = ''
  formState.manageLinkList = [
    {
      node: '1', //节点编号
      auditType: 0, //审批方式 0：按顺序审批；1：会签；2：或签
      auditUserId: '', //审批人，多人用逗号隔开
    },
  ]
}
const radioStyle = reactive({
  display: 'flex',
  height: '30px',
  lineHeight: '30px',
});
//穿梭框部分
const mockData = ref([]);

const targetKeys = ref<string[]>([]);
onMounted(() => {
  getMock();
});
const getMock = async () => {
  let queryparams: any = {
    pageSize: 1000,
    pageNum: 1,
    orderBy: [
      {
        field: 'createTime',
        order: 'desc',
      },
    ],
    paging: false,
  };
  const keys = [];
  const mData = [];
  let { result } = await userList(queryparams);
  let arr = result.filter((item) => item.identityCode && item.status == 1);
  arr.forEach((item) => {
    const data = {
      key: item.identityCode,
      title: item.name,
      description: item.name,
      chosen: false,
    };
    if (data.chosen) {
      keys.push(data.key);
    }
    mData.push(data);
  });
  mockData.value = mData;
  targetKeys.value = keys;
};
const filterOption = (inputValue: string, option) => {
  return option.description.indexOf(inputValue) > -1;
};
const handleChange = (keys: string[], direction: string, moveKeys: string[]) => {
  formState.manageLinkList[0].auditUserId = keys.join(',');
};

const handleSearch = (dir: string, value: string) => {
  console.log('search:', dir, value);
};
//提交
const submit = async () => {
  Modal.confirm({
    title: '确认保存吗?',
    onOk: async () => {
      try {
        await formRef.value.validateFields();
        const chars = formState.manageLinkList[0].auditUserId.split(',');
        console.log(chars, 2555555);
        if (chars.length != 2) return message.warning('选择人员应该为两人');
        if (addOrRenew > 0) {
          await getPutList({ ...formState, id: addOrRenew });
        } else {
          await getAddList(formState);
        }
        supertable.value?.refreshTable();
        onClose();
      } catch (errorInfo) {
        console.log('Failed:', errorInfo);
      }
    },
    onCancel() {
      console.log('Cancel');
    },
  });
};
</script>
<style lang="less" scoped>
.left {
  flex: 2;
  border-right: 1px solid #ccc;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 95%;

  .lan {
    width: 70%;
    height: 80px;
    background-color: #1677ff;
    border-radius: 6px;
    text-align: center;

    p {
      height: 50%;
      line-height: 40px;
      margin: 0;
      color: #fff;
    }
  }

  .bjin {
    background-color: #fff;
    color: rgb(102, 99, 99) !important;
    position: relative;

    .icon {
      position: absolute; //父元素需要相对定位
      top: 13px;
      right: 30px;
    }
  }
}

/deep/.ant-transfer {
  height: 100%;
}
</style>
